package com.shuwang.jh_shop.utils

import android.app.Activity
import android.os.Process

import java.util.Stack

/**
 * activity堆栈式管理

 * @author FireAnt（http://my.oschina.net/LittleDY）
 * *
 * @created 2014年10月30日 下午6:22:05
 */
class AppManager private constructor() {

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity) {
        activityStack!!.add(activity)
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity {
        val activity = activityStack!!.lastElement()
        return activity
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        val activity = activityStack!!.lastElement()
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null && activityStack!!.contains(activity)) {
            activityStack!!.remove(activity)
            activity.finish()
        }
    }

    /**
     * 结束指定的Activity
     */
    fun removeActivity(activity: Activity?) {
        if (activity != null && activityStack!!.contains(activity)) {
            activityStack!!.remove(activity)
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (activity in activityStack!!) {
            if (activity.javaClass == cls) {
                finishActivity(activity)
                break
            }
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        for (i in activityStack!!.indices) {
            if (null != activityStack!![i]) {
                activityStack!![i].finish()
            }
        }
        activityStack!!.clear()
    }

    val isNullStack: Boolean
        get() {
            return activityStack!!.size == 0
        }

    /**
     * 退出应用程序
     */
    fun AppExit() {
        try {
            finishAllActivity()
            Process.killProcess(Process.myPid())
            System.exit(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    companion object {

        private var activityStack: Stack<Activity>? = null
        private var instance: AppManager? = null

        /**
         * 单一实例
         */
        val appManager: AppManager
            get() {
                if (instance == null) {
                    instance = AppManager()
                }

                if (activityStack == null) {
                    activityStack = Stack<Activity>()
                }

                return instance!!
            }

        /**
         * 获取指定的Activity

         * @author kymjs
         */
        fun getActivity(cls: Class<*>): Activity? {
            if (activityStack != null)
                for (activity in activityStack!!) {
                    if (activity.javaClass == cls) {
                        return activity
                    }
                }
            return null
        }
    }
}
